home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / elispman.lha / elispman / macros.texi < prev    next >
Lisp/Scheme  |  1993-05-19  |  21KB  |  585 lines

  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Emacs Lisp Reference Manual.
  3. @c Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc. 
  4. @c See the file elisp.texi for copying conditions.
  5. @setfilename ../info/macros
  6. @node Macros, Loading, Functions, Top
  7. @chapter Macros
  8. @cindex macros
  9.  
  10.   @dfn{Macros} enable you to define new control constructs and other
  11. language features.  A macro is defined much like a function, but instead
  12. of telling how to compute a value, it tells how to compute another Lisp
  13. expression which will in turn compute the value.  We call this
  14. expression the @dfn{expansion} of the macro.
  15.  
  16.   Macros can do this because they operate on the unevaluated expressions
  17. for the arguments, not on the argument values as functions do.  They can
  18. therefore construct an expansion containing these argument expressions
  19. or parts of them.
  20.  
  21.   If you are using a macro to do something an ordinary function could
  22. do, just for the sake of speed, consider using an inline function
  23. instead.  @xref{Inline Functions}.
  24.  
  25. @menu
  26. * Simple Macro::            A basic example.
  27. * Expansion::               How, when and why macros are expanded.
  28. * Compiling Macros::        How macros are expanded by the compiler.
  29. * Defining Macros::         How to write a macro definition.
  30. * Backquote::               Easier construction of list structure.
  31. * Problems with Macros::    Don't evaluate the macro arguments too many times.
  32.                               Don't hide the user's variables.
  33. @end menu
  34.  
  35. @node Simple Macro, Expansion, Macros, Macros
  36. @section A Simple Example of a Macro
  37.  
  38.   Suppose we would like to define a Lisp construct to increment a
  39. variable value, much like the @code{++} operator in C.  We would like to
  40. write @code{(inc x)} and have the effect of @code{(setq x (1+ x))}.
  41. Here's a macro definition that does the job:
  42.  
  43. @findex inc
  44. @example
  45. @group
  46. (defmacro inc (var)
  47.    (list 'setq var (list '1+ var)))
  48. @end group
  49. @end example
  50.  
  51.   When this is called with @code{(inc x)}, the argument @code{var} has
  52. the value @code{x}---@emph{not} the @emph{value} of @code{x}.  The body
  53. of the macro uses this to construct the expansion, which is @code{(setq
  54. x (1+ x))}.  Once the macro definition returns this expansion, Lisp
  55. proceeds to evaluate it, thus incrementing @code{x}.
  56.  
  57. @node Expansion, Compiling Macros, Simple Macro, Macros
  58. @section Expansion of a Macro Call
  59. @cindex expansion of macros
  60. @cindex macro call
  61.  
  62.   A macro call looks just like a function call in that it is a list which
  63. starts with the name of the macro.  The rest of the elements of the list
  64. are the arguments of the macro.
  65.  
  66.   Evaluation of the macro call begins like evaluation of a function call
  67. except for one crucial difference: the macro arguments are the actual
  68. expressions appearing in the macro call.  They are not evaluated before
  69. they are given to the macro definition.  By contrast, the arguments of a
  70. function are results of evaluating the elements of the function call
  71. list.
  72.  
  73.   Having obtained the arguments, Lisp invokes the macro definition just
  74. as a function is invoked.  The argument variables of the macro are bound
  75. to the argument values from the macro call, or to a list of them in the
  76. case of a @code{&rest} argument.  And the macro body executes and
  77. returns its value just as a function body does.
  78.  
  79.   The second crucial difference between macros and functions is that the
  80. value returned by the macro body is not the value of the macro call.
  81. Instead, it is an alternate expression for computing that value, also
  82. known as the @dfn{expansion} of the macro.  The Lisp interpreter
  83. proceeds to evaluate the expansion as soon as it comes back from the
  84. macro.
  85.  
  86.   Since the expansion is evaluated in the normal manner, it may contain
  87. calls to other macros.  It may even be a call to the same macro, though
  88. this is unusual.
  89.  
  90.   You can see the expansion of a given macro call by calling
  91. @code{macroexpand}.
  92.  
  93. @defun macroexpand form &optional environment
  94. @cindex macro expansion
  95. This function expands @var{form}, if it is a macro call.  If the result
  96. is another macro call, it is expanded in turn, until something which is
  97. not a macro call results.  That is the value returned by
  98. @code{macroexpand}.  If @var{form} is not a macro call to begin with, it
  99. is returned as given.
  100.  
  101. Note that @code{macroexpand} does not look at the subexpressions of
  102. @var{form} (although some macro definitions may do so).  Even if they
  103. are macro calls themselves, @code{macroexpand} does not expand them.
  104.  
  105. The function @code{macroexpand} does not expand calls to inline functions.
  106. Normally there is no need for that, since a call to an inline function is
  107. no harder to understand than a call to an ordinary function.
  108.  
  109. If @var{environment} is provided, it specifies an alist of macro
  110. definitions that shadow the currently defined macros.  This is used
  111. by byte compilation.
  112.  
  113. @smallexample
  114. @group
  115. (defmacro inc (var)
  116.     (list 'setq var (list '1+ var)))
  117.      @result{} inc
  118. @end group
  119.  
  120. @group
  121. (macroexpand '(inc r))
  122.      @result{} (setq r (1+ r))
  123. @end group
  124.  
  125. @group
  126. (defmacro inc2 (var1 var2)
  127.     (list 'progn (list 'inc var1) (list 'inc var2)))
  128.      @result{} inc2
  129. @end group
  130.  
  131. @group
  132. (macroexpand '(inc2 r s))
  133.      @result{} (progn (inc r) (inc s))  ; @r{@code{inc} not expanded here.}
  134. @end group
  135. @end smallexample
  136. @end defun
  137.  
  138. @node Compiling Macros, Defining Macros, Expansion, Macros
  139. @section Macros and Byte Compilation
  140. @cindex byte-compiling macros
  141.  
  142.   You might ask why we take the trouble to compute an expansion for a
  143. macro and then evaluate the expansion.  Why not have the macro body
  144. produce the desired results directly?  The reason has to do with
  145. compilation.
  146.  
  147.   When a macro call appears in a Lisp program being compiled, the Lisp
  148. compiler calls the macro definition just as the interpreter would, and
  149. receives an expansion.  But instead of evaluating this expansion, it
  150. compiles the expansion as if it had appeared directly in the program.
  151. As a result, the compiled code produces the value and side effects
  152. intended for the macro, but executes at full compiled speed.  This would
  153. not work if the macro body computed the value and side effects
  154. itself---they would be computed at compile time, which is not useful.
  155.  
  156.   In order for compilation of macro calls to work, the macros must be
  157. defined in Lisp when the calls to them are compiled.  The compiler has a
  158. special feature to help you do this: if a file being compiled contains a
  159. @code{defmacro} form, the macro is defined temporarily for the rest of
  160. the compilation of that file.  To use this feature, you must define the
  161. macro in the same file where it is used and before its first use.
  162.  
  163.   While byte-compiling a file, any @code{require} calls at top-level are
  164. executed.  One way to ensure that necessary macro definitions are
  165. available during compilation is to require the file that defines them.
  166. @xref{Features}.
  167.  
  168. @node Defining Macros, Backquote, Compiling Macros, Macros
  169. @section Defining Macros
  170.  
  171.   A Lisp macro is a list whose @sc{car} is @code{macro}.  Its @sc{cdr} should
  172. be a function; expansion of the macro works by applying the function
  173. (with @code{apply}) to the list of unevaluated argument-expressions
  174. from the macro call.
  175.  
  176.   It is possible to use an anonymous Lisp macro just like an anonymous
  177. function, but this is never done, because it does not make sense to pass
  178. an anonymous macro to mapping functions such as @code{mapcar}.  In
  179. practice, all Lisp macros have names, and they are usually defined with
  180. the special form @code{defmacro}.
  181.  
  182. @defspec defmacro name argument-list body-forms@dots{}
  183. @code{defmacro} defines the symbol @var{name} as a macro that looks
  184. like this:
  185.  
  186. @example
  187. (macro lambda @var{argument-list} . @var{body-forms})
  188. @end example
  189.  
  190. This macro object is stored in the function cell of @var{name}.  The
  191. value returned by evaluating the @code{defmacro} form is @var{name}, but
  192. usually we ignore this value.
  193.  
  194. The shape and meaning of @var{argument-list} is the same as in a
  195. function, and the keywords @code{&rest} and @code{&optional} may be used
  196. (@pxref{Argument List}).  Macros may have a documentation string, but
  197. any @code{interactive} declaration is ignored since macros cannot be
  198. called interactively.
  199. @end defspec
  200.  
  201. @node Backquote, Problems with Macros, Defining Macros, Macros
  202. @section Backquote
  203. @cindex backquote (list substitution)
  204. @cindex ` (list substitution)
  205.  
  206.   It could prove rather awkward to write macros of significant size,
  207. simply due to the number of times the function @code{list} needs to be
  208. called.  To make writing these forms easier, a macro @samp{`}
  209. (often called @dfn{backquote}) exists.
  210.  
  211.   Backquote allows you to quote a list, but selectively evaluate
  212. elements of that list.  In the simplest case, it is identical to the
  213. special form @code{quote} (@pxref{Quoting}).  For example, these
  214. two forms yield identical results:
  215.  
  216. @example
  217. @group
  218. (` (a list of (+ 2 3) elements))
  219.      @result{} (a list of (+ 2 3) elements)
  220. @end group
  221. @group
  222. (quote (a list of (+ 2 3) elements))
  223.      @result{} (a list of (+ 2 3) elements)
  224. @end group
  225. @end example
  226.  
  227. @findex ,
  228. By inserting a special marker, @samp{,}, inside of the argument
  229. to backquote, it is possible to evaluate desired portions of the
  230. argument:
  231.  
  232. @example
  233. @group
  234. (list 'a 'list 'of (+ 2 3) 'elements)
  235.      @result{} (a list of 5 elements)
  236. @end group
  237. @group
  238. (` (a list of (, (+ 2 3)) elements))
  239.      @result{} (a list of 5 elements)
  240. @end group
  241. @end example
  242.  
  243. @findex ,@@
  244. @cindex splicing (with backquote)
  245. It is also possible to have an evaluated list @dfn{spliced} into the
  246. resulting list by using the special marker @samp{,@@}.  The elements of
  247. the spliced list become elements at the same level as the other elements
  248. of the resulting list.  The equivalent code without using @code{`} is
  249. often unreadable.  Here are some examples:
  250.  
  251. @example
  252. @group
  253. (setq some-list '(2 3))
  254.      @result{} (2 3)
  255. @end group
  256. @group
  257. (cons 1 (append some-list '(4) some-list))
  258.      @result{} (1 2 3 4 2 3)
  259. @end group
  260. @group
  261. (` (1 (,@@ some-list) 4 (,@@ some-list)))
  262.      @result{} (1 2 3 4 2 3)
  263. @end group
  264.  
  265. @group
  266. (setq list '(hack foo bar))
  267.      @result{} (hack foo bar)
  268. @end group
  269. @group
  270. (cons 'use
  271.   (cons 'the
  272.     (cons 'words (append (cdr list) '(as elements)))))
  273.      @result{} (use the words foo bar as elements)
  274. @end group
  275. @group
  276. (` (use the words (,@@ (cdr list)) as elements (,@@ nil)))
  277.      @result{} (use the words foo bar as elements)
  278. @end group
  279. @end example
  280.  
  281. The reason for @code{(,@@ nil)} is to avoid a bug in Emacs version 18.
  282. The bug occurs when a call to @code{,@@} is followed only by constant
  283. elements.  Thus,
  284.  
  285. @example
  286. (` (use the words (,@@ (cdr list)) as elements))
  287. @end example
  288.  
  289. @noindent
  290. would not work, though it really ought to.  @code{(,@@ nil)} avoids the
  291. problem by being a nonconstant element that does not affect the result.
  292.  
  293. @defmac ` list
  294. This macro returns @var{list} as @code{quote} would, except that the
  295. list is copied each time this expression is evaluated, and any sublist
  296. of the form @code{(, @var{subexp})} is replaced by the value of
  297. @var{subexp}.  Any sublist of the form @code{(,@@ @var{listexp})}
  298. is replaced by evaluating @var{listexp} and splicing its elements
  299. into the containing list in place of this sublist.  (A single sublist
  300. can in this way be replaced by any number of new elements in the
  301. containing list.)
  302.  
  303. There are certain contexts in which @samp{,} would not be recognized and
  304. should not be used:
  305.  
  306. @smallexample
  307. @group
  308. ;; @r{Use of a @samp{,} expression as the @sc{cdr} of a list.}
  309. (` (a . (, 1)))                             ; @r{Not @code{(a . 1)}}
  310.      @result{} (a \, 1)                                
  311. @end group
  312.  
  313. @group
  314. ;; @r{Use of @samp{,} in a vector.}
  315. (` [a (, 1) c])                             ; @r{Not @code{[a 1 c]}}
  316.      @error{} Wrong type argument                      
  317. @end group
  318.  
  319. @group
  320. ;; @r{Use of a @samp{,} as the entire argument of @samp{`}.}
  321. (` (, 2))                                   ; @r{Not 2}
  322.      @result{} (\, 2)                                  
  323. @end group
  324. @end smallexample
  325. @end defmac
  326.  
  327. @cindex CL note---@samp{,}, @samp{,@@} as functions
  328. @quotation
  329. @b{Common Lisp note:} in Common Lisp, @samp{,} and @samp{,@@} are implemented
  330. as reader macros, so they do not require parentheses.  Emacs Lisp implements
  331. them as functions because reader macros are not supported (to save space).
  332. @end quotation
  333.  
  334. @node Problems with Macros,, Backquote, Macros
  335. @section Common Problems Using Macros
  336.  
  337.   The basic facts of macro expansion have all been described above, but
  338. there consequences are often counterintuitive.  This section describes
  339. some important consequences that can lead to trouble, and rules to follow
  340. to avoid trouble.
  341.  
  342. @menu
  343. * Argument Evaluation::    The expansion should evaluate each macro arg once.
  344. * Surprising Local Vars::  Local variable bindings in the expansion
  345.                               require special care.
  346. * Eval During Expansion::  Don't evaluate them; put them in the expansion.
  347. * Repeated Expansion::     Avoid depending on how many times expansion is done.
  348. @end menu
  349.  
  350. @node Argument Evaluation, Surprising Local Vars, Problems with Macros, Problems with Macros
  351. @subsection Evaluating Macro Arguments Too Many Times
  352.  
  353.   When defining a macro you must pay attention to the number of times
  354. the arguments will be evaluated when the expansion is executed.  The
  355. following macro (used to facilitate iteration) illustrates the problem.
  356. This macro allows us to write a simple ``for'' loop such as one might
  357. find in Pascal.
  358.  
  359. @findex for
  360. @smallexample
  361. @group
  362. (defmacro for (var from init to final do &rest body)
  363.   "Execute a simple \"for\" loop, e.g.,
  364.     (for i from 1 to 10 do (print i))."
  365.   (list 'let (list (list var init))
  366.         (cons 'while (cons (list '<= var final)
  367.                            (append body (list (list 'inc var)))))))
  368. @end group
  369. @result{} for
  370.  
  371. @group
  372. (for i from 1 to 3 do
  373.    (setq square (* i i))
  374.    (princ (format "\n%d %d" i square)))
  375. @expansion{}
  376. @end group
  377. @group
  378. (let ((i 1))
  379.   (while (<= i 3)
  380.     (setq square (* i i))
  381.     (princ (format "%d      %d" i square))
  382.     (inc i)))
  383. @end group
  384. @group
  385.  
  386.      @print{}1       1
  387.      @print{}2       4
  388.      @print{}3       9
  389. @result{} nil
  390. @end group
  391. @end smallexample
  392.  
  393. @noindent
  394. (The arguments @code{from}, @code{to}, and @code{do} in this macro are
  395. ``syntactic sugar''; they are entirely ignored.  The idea is that you
  396. will write noise words (such as @code{from}, @code{to}, and @code{do})
  397. in those positions in the macro call.)
  398.  
  399. This macro suffers from the defect that @var{final} is evaluated on
  400. every iteration.  If @var{final} is a constant, this is not a problem.
  401. If it is a more complex form, say @code{(long-complex-calculation x)},
  402. this can slow down the execution significantly.  If @var{final} has side
  403. effects, executing it more than once is probably incorrect.
  404.  
  405. @cindex macro argument evaluation
  406. A well-designed macro definition takes steps to avoid this problem by
  407. producing an expansion that evaluates the argument expressions exactly
  408. once unless repeated evaluation is part of the intended purpose of the
  409. macro.  Here is a correct expansion for the @code{for} macro:
  410.  
  411. @smallexample
  412. @group
  413. (let ((i 1)
  414.       (max 3))
  415.   (while (<= i max)
  416.     (setq square (* i i))
  417.     (princ (format "%d      %d" i square))
  418.     (inc i)))
  419. @end group
  420. @end smallexample
  421.  
  422. Here is a macro definition that creates this expansion: 
  423.  
  424. @smallexample
  425. @group
  426. (defmacro for (var from init to final do &rest body)
  427.   "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  428.   (` (let (((, var) (, init))
  429.            (max (, final)))
  430.        (while (<= (, var) max)
  431.          (,@@ body)
  432.          (inc (, var))))))
  433. @end group
  434. @end smallexample
  435.  
  436.   Unfortunately, this introduces another problem.
  437. @ifinfo
  438. Proceed to the following node.
  439. @end ifinfo
  440.  
  441. @node Surprising Local Vars, Eval During Expansion, Argument Evaluation, Problems with Macros
  442. @subsection Local Variables in Macro Expansions
  443.  
  444. @ifinfo
  445.   In the previous section, the definition of @code{for} was fixed as
  446. follows to make the expansion evaluate the macro arguments the proper
  447. number of times:
  448.  
  449. @smallexample
  450. @group
  451. (defmacro for (var from init to final do &rest body)
  452.   "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  453. @end group
  454. @group
  455.   (` (let (((, var) (, init))
  456.            (max (, final)))
  457.        (while (<= (, var) max)
  458.          (,@@ body)
  459.          (inc (, var))))))
  460. @end group
  461. @end smallexample
  462. @end ifinfo
  463.  
  464.   The new definition of @code{for} has a new problem: it introduces a
  465. local variable named @code{max} which the user does not expect.  This
  466. causes trouble in examples such as the following:
  467.  
  468. @example
  469. @group
  470. (let ((max 0))
  471.   (for x from 0 to 10 do
  472.     (let ((this (frob x)))
  473.       (if (< max this)
  474.           (setq max this)))))
  475. @end group
  476. @end example
  477.  
  478. @noindent
  479. The references to @code{max} inside the body of the @code{for}, which
  480. are supposed to refer to the user's binding of @code{max}, really access
  481. the binding made by @code{for}.
  482.  
  483. The way to correct this is to use an uninterned symbol instead of
  484. @code{max} (@pxref{Creating Symbols}).  The uninterned symbol can be
  485. bound and referred to just like any other symbol, but since it is created
  486. by @code{for}, we know that it cannot appear in the user's program.
  487. Since it is not interned, there is no way the user can put it into the
  488. program later.  It will never appear anywhere except where put by
  489. @code{for}.  Here is a definition of @code{for} which works this way:
  490.  
  491. @smallexample
  492. @group
  493. (defmacro for (var from init to final do &rest body)
  494.   "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  495.   (let ((tempvar (make-symbol "max")))
  496.     (` (let (((, var) (, init))
  497.              ((, tempvar) (, final)))
  498.          (while (<= (, var) (, tempvar))
  499.                 (,@@ body)
  500.                 (inc (, var)))))))
  501. @end group
  502. @end smallexample
  503.  
  504. @noindent
  505. This creates an uninterned symbol named @code{max} and puts it in the
  506. expansion instead of the usual interned symbol @code{max} that appears
  507. in expressions ordinarily.
  508.  
  509. @node Eval During Expansion, Repeated Expansion, Surprising Local Vars, Problems with Macros
  510. @subsection Evaluating Macro Arguments in Expansion
  511.  
  512.   Another problem can happen if you evaluate any of the macro argument
  513. expressions during the computation of the expansion, such as by calling
  514. @code{eval} (@pxref{Eval}).  If the argument is supposed to refer to the
  515. user's variables, you may have trouble if the user happens to use a
  516. variable with the same name as one of the macro arguments.  Inside the
  517. macro body, the macro argument binding is the most local binding of this
  518. variable, so any references inside the form being evaluated do refer
  519. to it.  Here is an example:
  520.  
  521. @example
  522. @group
  523. (defmacro foo (a)
  524.   (list 'setq (eval a) t))
  525.      @result{} foo
  526. @end group
  527. @group
  528. (setq x 'b)
  529. (foo x) @expansion{} (setq b t)
  530.      @result{} t                  ; @r{and @code{b} has been set.}
  531. ;; @r{but}
  532. (setq a 'b)
  533. (foo a) @expansion{} (setq 'b t)     ; @r{invalid!}
  534. @error{} Symbol's value is void: b
  535. @end group
  536. @end example
  537.  
  538.   It makes a difference whether the user types @code{a} or @code{x},
  539. because @code{a} conflicts with the macro argument variable @code{a}.
  540.  
  541.   In general it is best to avoid calling @code{eval} in a macro
  542. definition at all.  
  543.  
  544. @node Repeated Expansion,, Eval During Expansion, Problems with Macros
  545. @subsection How Many Times is the Macro Expanded?
  546.  
  547.   Occasionally problems result from the fact that a macro call is
  548. expanded each time it is evaluated in an interpreted function, but is
  549. expanded only once (during compilation) for a compiled function.  If the
  550. macro definition has side effects, they will work differently depending
  551. on how many times the macro is expanded.
  552.  
  553.   In particular, constructing objects is a kind of side effect.  If the
  554. macro is called once, then the objects are constructed only once.  In
  555. other words, the same structure of objects is used each time the macro
  556. call is executed.  In interpreted operation, the macro is reexpanded
  557. each time, producing a fresh collection of objects each time.  Usually
  558. this does not matter---the objects have the same contents whether they
  559. are shared or not.  But if the surrounding program does side effects
  560. on the objects, it makes a difference whether they are shared.  Here is
  561. an example:
  562.  
  563. @lisp
  564. @group
  565. (defmacro new-object ()
  566.   (list 'quote (cons nil nil)))
  567. @end group
  568.  
  569. @group
  570. (defun initialize (condition)
  571.   (let ((object (new-object)))
  572.     (if condition
  573.     (setcar object condition))
  574.     object))
  575. @end group
  576. @end lisp
  577.  
  578. @noindent
  579. If @code{initialize} is interpreted, a new list @code{(nil)} is
  580. constructed each time @code{initialize} is called.  Thus, no side effect
  581. survives between calls.  If @code{initialize} is compiled, then the
  582. macro @code{new-object} is expanded during compilation, producing a
  583. single ``constant'' @code{(nil)} that is reused and altered each time
  584. @code{initialize} is called.
  585.